package com.xiangzi.xzschedule.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerListener;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;

import com.xiangzi.xzschedule.job.PrintTimeJob;
import com.xiangzi.xzschedule.quartz.listener.MyJobListener;
import com.xiangzi.xzschedule.quartz.listener.MySchedulerListener;
import com.xiangzi.xzschedule.quartz.listener.MyTriggerListener;

public class SimpleSchedule {

	public static void main(String[] args) throws SchedulerException,
			InterruptedException {
		String jobGroup = "defaultGroup";
		String jobName = "PrintTimeJob";
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		Scheduler scheduler = schedulerFactory.getScheduler();
		
		//addSchedulerListener
		SchedulerListener mySchedulerListener = new MySchedulerListener();
		scheduler.getListenerManager().addSchedulerListener(mySchedulerListener);
		
		scheduler.start();
		JobDetail jobDetail = JobBuilder.newJob(PrintTimeJob.class)
				.withIdentity(jobName, jobGroup).build();

		// 表达式调度构建器
		CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder
				.cronSchedule("0/2 * * * * ?");
		// 按新的cronExpression表达式构建一个新的trigger
		Trigger trigger = TriggerBuilder.newTrigger()
				.withIdentity(jobName, jobGroup)
				.withSchedule(cronScheduleBuilder).build();

		// TriggerBuilder.newTrigger().withIdentity(jobName,
		// jobGroup).withIdentity(triggerKey);

		scheduler.scheduleJob(jobDetail, trigger);

		scheduler.getListenerManager().addJobListener(new MyJobListener(),
				KeyMatcher.keyEquals(new JobKey(jobName, jobGroup)));
		scheduler.getListenerManager().addTriggerListener(
				new MyTriggerListener(),
				KeyMatcher.keyEquals(new TriggerKey(jobName, jobGroup)));
		
		Thread.sleep(1000 * 60);
		
		//Removing a SchedulerListener
		scheduler.getListenerManager().removeSchedulerListener(mySchedulerListener);
		
		scheduler.shutdown();
	}
}
